<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 按钮区域 -->
      <el-row>
        <e-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        </e-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolesList" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdBottom', i1 === 0 ? 'bdTop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col span="5">
                <el-tag
                  closable
                  @close="removeRightsById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col span="19">
                <!-- 通过循环渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdTop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col span="18">
                    <!-- 通过循环渲染三级权限 -->
                    <el-row v-for="item3 in item2.children" :key="item3.id">
                      <el-col>
                        <el-tag
                          type="warning"
                          closable
                          @close="removeRightsById(scope.row, item3.id)"
                          >{{ item3.authName }}</el-tag
                        >
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="showDeleteConfirm(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="dialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <!-- 内容主体 -->
        <el-form
          :model="addRoleForm"
          :rules="addRoleFormRules"
          ref="addRoleFormRef"
          label-width="70px"
        >
          <el-form-item prop="roleName" label="角色名称" label-width="90px">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item prop="roleDesc" label="角色描述" label-width="90px">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色对话框 -->
      <el-dialog
        title="编辑角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <!-- 内容主体 -->
        <el-form
          :model="editRoleForm"
          :rules="editRoleFormRules"
          ref="editRoleFormRef"
          label-width="70px"
        >
          <el-form-item prop="roleName" label="角色名称" label-width="90px">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item prop="roleDesc" label="角色描述" label-width="90px">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="rightDialogVisible"
        width="50%"
        @close="setRightDialogClosed"
      >
        <!--树形控件 -->
        <el-tree
          :data="rightsList"
          :props="rightProps"
          show-checkbox
          :default-expand-all="true"
          node-key="id"
          :default-checked-keys="leafKeys"
          ref="treeRef"
        ></el-tree>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="rightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: {},
      // 树形权限数据
      rightsList: [],
      dialogVisible: false,
      editDialogVisible: false,
      rightDialogVisible: false,
      editRoleForm: {},
      // 树形控件树形绑定对象
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中节点集合
      leafKeys: [],
      // 当前即将分配权限的角色的ID
      roleId: '',
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.getRolesList()
  },

  methods: {
    //   获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 关闭对话框
    addDialogClose() {
      // 重置表单
      this.$refs.addRoleFormRef.resetFields()
    },
    editDialogClose() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 添加角色
    addRole() {
      // 表单预验证
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.dialogVisible = false
        this.getRolesList()
        this.$message.success('添加角色成功')
      })
    },
    // 显示编辑对话框
    async showEditDialog(id) {
      // 查询角色信息
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败')
      }
      this.editRoleForm = res.data
      this.editDialogVisible = true
    },
    // 编辑角色
    async editRole() {
      const { data: res } = await this.$http.put(
        'roles/' + this.editRoleForm.roleId,
        {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('编辑角色失败')
      }
      this.$message.success('编辑角色成功')
      this.getRolesList()
      this.editDialogVisible = false
    },
    // 删除角色弹出框
    showDeleteConfirm(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deletaRole(id)
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 发起删除角色请求
    async deletaRole(id) {
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('角色删除失败')
      }
      // 刷新列表
      this.getRolesList()
      this.$message.success('角色删除成功')
    },
    // 删除权限
    removeRightsById(row, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${row.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除权限失败')
          }
          // 不更新全部列表，只更改当前选中，防止重载导致页面收起
          row.children = res.data
          this.$message.success('删除权限成功')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 展示分配权限对话框
    async showRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsList = res.data
      this.getLeafkeys(role, this.leafKeys)
      this.rightDialogVisible = true
    },
    // 递归获取三级节点id集合
    getLeafkeys(node, arr) {
      // 不存在子节点说明为第三级结点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafkeys(item, arr)
      })
    },
    // 关闭权限对话框
    setRightDialogClosed() {
      // 重置数组
      this.leafKeys = []
    },
    // 点击分配权限
    async allotRights() {
      // 获取全选节点和半选节点数组并合并
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 分割为字符串
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.rightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdTop {
  border-top: 1px solid #eee;
}

.bdBottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
